package beanstao.util.collections;

import beanstao.util.Strings;
import beanstao.util.Util;

/**
 * 简便的名值对实现
 */
public class KeyValue<T> implements org.apache.commons.collections.KeyValue
{

	public static KeyValue<String> create(String s)
	{
		String[] ss = Strings.splitIgnoreBlank(s, "=");
		String name = null;
		String value = null;
		String pattern = PTN_3;
		if (null != ss)
		{
			if (ss.length == 1)
			{
				name = ss[0];
			}
			else if (ss.length == 2)
			{
				name = ss[0];
				if (ss[1].length() > 0)
				{
					if (ss[1].charAt(0) == '"')
					{
						value = ss[1].substring(1, ss[1].length() - 2);
						pattern = PTN_3;
					}
					else if (ss[1].charAt(0) == '\'')
					{
						value = ss[1].substring(1, ss[1].length() - 2);
						pattern = PTN_2;
					}
					else
					{
						value = ss[1];
						pattern = PTN_1;
					}
				}
			}
		}
		KeyValue<String> re = new KeyValue<String>(name, value);
		re.pattern = pattern;
		return re;
	}

	public KeyValue()
	{
	}

	private static final String PTN_1 = "%s=%s";
	private static final String PTN_2 = "%s='%s'";
	private static final String PTN_3 = "%s=\"%s\"";

	public KeyValue(String name, T value)
	{
		this.name = name;
		this.value = value;
		this.pattern = PTN_3;
	}

	private String name;

	private T value;

	private String pattern;

	public String getName()
	{
		return this.name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public T getValue()
	{
		return this.value;
	}

	@Override
	public Object getKey()
	{
		return this.getValue();
	}

	public String getString()
	{
		return this.value == null ? null : this.value.toString();
	}

	public void setValue(T value)
	{
		this.value = value;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
		{
			return true;
		}
		if (obj instanceof KeyValue<?>)
		{
			if (Strings.equals(((KeyValue<?>) obj).name, this.name))
			{
				Util.equals(((KeyValue<?>) obj).value, this.value);
			}
		}
		return false;
	}

	@Override
	public int hashCode()
	{
		return this.value.hashCode();
	}

	@Override
	public String toString()
	{
		String v = null == this.value ? "" : this.value.toString();
		v = v.replace("\"", "&quot;");
		return String.format(this.pattern, this.name, v);
	}

}
